package com.xxl.job.executor.util;

import com.alibaba.cloudapi.sdk.client.ApacheHttpClient;
import com.alibaba.cloudapi.sdk.constant.SdkConstant;
import com.alibaba.cloudapi.sdk.enums.HttpMethod;
import com.alibaba.cloudapi.sdk.enums.ParamPosition;
import com.alibaba.cloudapi.sdk.enums.Scheme;
import com.alibaba.cloudapi.sdk.model.ApiRequest;
import com.alibaba.cloudapi.sdk.model.ApiResponse;
import com.alibaba.cloudapi.sdk.model.HttpClientBuilderParams;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author dingfeng
 * @version 1.0
 * @date 2022/1/9 14:55
 * 发送阿里数据中台接口Api的请求类
 */
@Slf4j
@Component
public class HttpApiClient extends ApacheHttpClient {

    public void init(HttpClientBuilderParams httpClientBuilderParams){

        super.init(httpClientBuilderParams);
    }

    public ApiResponse query(String path, String method, Map<String, String> params) {
        try {
            ApiRequest request = new ApiRequest(HttpMethod.GET , path);
            if ("post".equals(method)) {
                request = new ApiRequest(HttpMethod.POST_FORM, path);
            }
            if (params != null) {
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    request.addParam(entry.getKey() , entry.getValue() , ParamPosition.QUERY , true);
                }
            }
            return sendSyncRequest(request);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("请求数据失败:{}",e.getMessage());
            return null;
        }

    }
    public static void main(String[] args) {
        HttpApiClient httpApiClient = new HttpApiClient();
        HttpClientBuilderParams httpParam = new HttpClientBuilderParams();
        httpParam.setAppKey("203811500");
        httpParam.setAppSecret("zmlqdt6lu3g02kk2fzizrar6cd2cs9wg");
        httpParam.setHost("06b8a04ab325450a9af47c2bbf41ad5e-cn-shenzhen.alicloudapi.com");
        httpParam.setScheme(Scheme.HTTP);
        httpApiClient.init(httpParam);
        HashMap<String, String> params = new HashMap<>();
        params.put("appCode","1321321");
        ApiResponse apiResponse = httpApiClient.query(
                "/data/graph/tianqi", "get", params);
        String response = new String(apiResponse.getBody() , SdkConstant.CLOUDAPI_ENCODING);
    }

}
